<?php

class Maven_ManageCatalogSpr_Model_Mysql4_Temp_Sprstock extends Mage_Core_Model_Mysql4_Abstract
{
	protected $_table;
	protected $_productEntityTable;
	protected $_productEntityVarchar;
	protected $_productEntityDecimal;

	public function _construct()
	{
		$this->_init('managecatalogspr/temp_sprstock', 'id');
		$this->_table = $this->getTable('managecatalogspr/temp_sprstock');
		$productEntity = Mage::getResourceModel('catalog/product');
		$this->_productEntityTable = $productEntity->getTable('catalog_product_entity');
		$this->_productEntityVarchar = $productEntity->getTable('catalog_product_entity_varchar');
		$this->_productEntityDecimal = $productEntity->getTable('catalog_product_entity_decimal');
        

	}
	public function getCountData($estatus='')
	{
		$select = $this->_getReadAdapter()->select()
		->from(array('main_table'=>$this->getTable('managecatalogspr/temp_sprstock')),
		array('total'=>'count(id)'));
		if($estatus!='')
		$select->where('main_table.status in ('.$estatus.')');
		$res = $this->_getReadAdapter()->fetchAll($select);
		if(isset($res[0]['total'])) {
			return $res[0]['total'];
		}
	}
	public function getSuccessCount()
	{
		return $this->getCountData(1);
	}
	public function getFailCount()
	{
		return $this->getCountData(2);
	}

	public function getPendingCount()
	{
		return $this->getCountData(0);
	}

	
	public function loadDataOperation($file)
	{
		$con = $this->_getWriteAdapter();
		$datas=file($file);
		foreach($datas as $key=>$data){
            if($key != 0 && $key != 1){
                    $qtyprefix=substr($data,0,2);
                    $item=substr($data,2,15);
                    $sku=trim($item);
                    $status=substr($data,17,1);
                    $unitMes=substr($data,18,2);
                    $len=substr($data,20,-1);
                    $j=20;$split=6;
                    $value=""; $field=""; $ffield="";$fvalue=""; $total=""; 
                    $loop=strlen($len)/$split;
				    $inv=array();
                    for($i=1;$i<=$loop;$i++){
                        $field.='qohdc'.$i.",";
                        $value.=substr($data,$j,$split).',';
                        $higvalue=substr($data,$j,$split);
                        $inv[$i]=$higvalue;
						$total=$total+$higvalue;
                        $j=$j+6;    
                    }
					 $highStock=$total;
					//$highStock = max($inv);
					
                    $ffield = substr($field, 0, -1); 
                    $fvalue = substr($value, 0, -1);
                    $con->query("INSERT INTO ".$this->_table."(rectype, sku, qty, astat, spruom, $ffield)
                        VALUES ('$qtyprefix','$sku', $highStock,'$status','$unitMes', $fvalue)");
            }
          }  
	}
	
	public function loadDataInfile($file)
	{
		try {
				
         	$con = $this->_getWriteAdapter();
			$con->query("TRUNCATE TABLE {$this->getTable('managecatalogspr/temp_sprstock')} ");
			
			//load data in to table
			$this->loadDataOperation($file);
            
            $con->query("UPDATE {$this->getTable('managecatalogspr/temp_sprstock')} SET sku = REPLACE(sku,'-','')");
           
           	//delete row which sku not exist.
			$con->query("DELETE `ts`.* FROM {$this->getTable('managecatalogspr/temp_sprstock')} AS `ts`
			LEFT JOIN {$this->_productEntityTable} AS `e`
			USING ( sku )
			WHERE `e`.`sku` IS NULL");
            
           	$priceId=$this->getAttrributeId("price");
			$weightId=$this->getAttrributeId("weight");
            
			$con->query("UPDATE {$this->getTable('managecatalogspr/temp_sprstock')} as ts SET ts.is_in_stock = IF(ts.qty > 0,1,0)
		    WHERE ts.sku IN (
			SELECT `e`.sku FROM {$this->_productEntityTable} AS `e` 
				INNER JOIN {$this->_productEntityDecimal} AS `_table_price` 
				ON (_table_price.entity_id = e.entity_id) AND (_table_price.attribute_id='$priceId') AND (_table_price.store_id=0) 
				INNER JOIN {$this->_productEntityDecimal} AS `_table_weight` ON (_table_weight.entity_id = e.entity_id) AND (_table_weight.attribute_id='$weightId') AND (_table_weight.store_id=0) 
				WHERE (_table_price.value > 1) AND (_table_weight.value > 0))");
				
			// update product_id
			$con->query("UPDATE {$this->getTable('managecatalogspr/temp_sprstock')} as ts,
			{$this->_productEntityTable} AS `e`
				SET ts.product_id = e.entity_id
				WHERE ts.sku = `e`.sku");
	 	}catch (Exception $e) {
			die($e->getMessage());
		}
	}
	public function updateProductStock()
	{
		$stockEntity = Mage::getResourceModel('cataloginventory/stock');

		$stockEntity->getTable('stock_item');
		$stockEntity->getTable('stock_status');

		$this->_getWriteAdapter()->query("UPDATE 
		{$stockEntity->getTable('stock_item')} AS s_i SET s_i.qty = 0, s_i.is_in_stock = 0;");
        
        $this->_getWriteAdapter()->query("UPDATE
		{$stockEntity->getTable('stock_status')} AS s_s  SET s_s.qty = 0, s_s.stock_status = 0;");
		
		
		$this->_getWriteAdapter()->query("UPDATE
		{$stockEntity->getTable('stock_item')} AS s_i,
		{$stockEntity->getTable('stock_status')} AS s_s,
		{$this->_table} AS ts
		    SET s_i.qty = ts.qty, s_i.is_in_stock = ts.is_in_stock,
	                s_s.qty = ts.qty, s_s.stock_status = IF(ts.qty > 0,1,0) , ts.status=1
        	WHERE s_i.product_id = ts.product_id AND s_i.product_id = s_s.product_id ");		
	}
	
	public function getAttrributeId($code)
	{
		if($code) {
			$installer = new Mage_Catalog_Model_Resource_Eav_Mysql4_Setup('core_setup');
			$attributeId = $installer->getAttributeId('catalog_product', $code);
			return $attributeId;
		}else return "";
	}
}